from backend.models import DailyStatistics
from frontend.models import KeyWord
import datetime
import hashlib
from email.mime.text import MIMEText
from email.header import Header
import smtplib
from private_info import email_auth

def DailyStatisticsAdd(field:str):
    """
    统计每日新增
    field:
    - login:登录次数
    - search:搜索次数
    - comment:评论数
    - collection:收藏数
    - useradd:用户数
    """
    if not DailyStatistics.objects.filter(date=datetime.date.today()) :
        DailyStatistics.objects.create(**{'date':datetime.date.today(),field:1})
    else:
        record = DailyStatistics.objects.get(date=datetime.date.today())
        record.__dict__[field] += 1
        record.save()

def KeyWordRecord(keyword):
    """
    记录被使用的关键字和使用次数
    """
    if KeyWord.objects.filter(keyword=keyword) :
        key = KeyWord.objects.get(keyword=keyword)
        key.count = key.count+1
        key.save()
    else:
        KeyWord.objects.create(keyword=keyword)


def updateCookies(response,**kwargs):
    """
    更新cookie
    """
    for k,v in kwargs.items():
        if v != None: response.set_cookie(k,v,path='/',max_age=15*24*3600)
    return response

def strmd5(string):
    """
    md5加密字符串
    """
    m2 = hashlib.md5()
    m2.update(string.encode('utf-8'))
    string = m2.hexdigest()
    return string


def sendMessage(msg, email,subject,conten_type='plain',name='尊敬的用户'):
    """
    邮件通知
    """
   # 第三方 SMTP 服务
    mail_host = "smtp.qq.com"  # 设置服务器
    mail_user = "1297416662@qq.com"  # 用户名
    mail_pass = email_auth  # 授权码
    sender = '1297416662@qq.com'
    receivers = [email]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
    message = MIMEText(msg, conten_type, 'utf-8')
    message['From'] = Header("Price比价平台", 'utf-8')  # 括号里的对应发件人邮箱昵称（随便起）、发件人邮箱账号
    message['To'] = Header(name, 'utf-8')  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    message['Subject'] = Header(subject, 'utf-8')
    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 发件人邮箱中的SMTP服务器，端口是25 (腾讯云服务器 端口为587)
        smtpObj.login(mail_user, mail_pass)
        resp=smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")
